package com.ikingtech.framework.sdk.log.embedded.appender;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.filter.ThresholdFilter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.ikingtech.framework.sdk.log.embedded.appender.consumer.LogConsumer;
import com.ikingtech.framework.sdk.log.embedded.properties.LogProperties;
import lombok.RequiredArgsConstructor;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;

import static com.ikingtech.framework.sdk.context.constant.CommonConstants.LOG_CONSUMER_RUNNER_ORDER;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class LogAppender extends UnsynchronizedAppenderBase<ILoggingEvent> implements ApplicationRunner, Ordered {

    private final LogProperties properties;

    @Override
    protected void append(ILoggingEvent iLoggingEvent) {
        LogConsumer.cacheLog(iLoggingEvent);
    }

    @Override
    public void run(ApplicationArguments args) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        context.getLogger("ROOT").addAppender(LogAppender.this);
        ThresholdFilter filter = new ThresholdFilter();
        filter.setLevel(this.properties.getLevel());
        filter.setContext(context);
        filter.start();
        this.addFilter(filter);
        this.setContext(context);
        new LogConsumer().start();
        super.start();
    }

    @Override
    public int getOrder() {
        return LOG_CONSUMER_RUNNER_ORDER;
    }
}
